package com.wltt.product.ahuthr.service;

import com.wltt.product.ahuthr.component.AgreementComponent;
import com.wltt.product.ahuthr.config.exception.BusinessException;
import com.wltt.product.ahuthr.mapper.*;
import com.wltt.product.ahuthr.model.ResultData;
import com.wltt.product.ahuthr.model.bo.AgreementBO;
import com.wltt.product.ahuthr.model.po.*;
import com.wltt.product.ahuthr.model.vo.*;
import com.wltt.product.ahuthr.model.vo.base.AgreementAttributeVO;
import com.wltt.product.ahuthr.model.vo.base.AttachFileVO;
import com.wltt.product.ahuthr.service.base.BaseServiceImpl;
import jakarta.annotation.Resource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @ClassName: AgreementServiceImpl
 * @Description: 人员协议 逻辑服务类<br/>
 * 不做业务校验，参数校验统一放到前置的Service中
 * @Date: 2024-08-07 09:50:27
 * @Author yanggl
 */
@Service(value = "agreementService")
public class AgreementServiceImpl extends BaseServiceImpl<AgreementPO, Long> implements AgreementService {

    private static final Logger logger = LogManager.getLogger(AgreementServiceImpl.class);

    private AgreementMapper agreementMapper;

    @Resource
    private SystemAgreementTypeMapper systemAgreementTypeMapper;

    @Resource
    private SystemAgreementAttributeMapper systemAgreementAttributeMapper;

    @Resource
    private AgreementAttributeMapper agreementAttributeMapper;

    @Resource
    private AgreementAttachFileMapper agreementAttachFileMapper;

    @Resource
    private AttachFileMapper attachFileMapper;

    @Resource
    private AgreementComponent agreementComponent;

    //构造方法
    public AgreementServiceImpl(AgreementMapper agreementMapper) {
        super(agreementMapper);
        this.agreementMapper = agreementMapper;
    }

    /**
     * 查询列表
     *
     * @return
     */
    @Override
    public ResultData listAll(AgreementListReq agreementListReq) {
        Long userId = agreementListReq.getUserId();
        if (null == userId) {
            throw new BusinessException("未指定人员", HttpStatus.BAD_REQUEST);
        }
        List<AgreementBO> agreementBOList = agreementMapper.queryByUserId(userId);
        List<AgreementListRsp> agreementListRspList = Optional.ofNullable(agreementBOList).orElse(new ArrayList<>())
                .stream().map(bo -> {
                    AgreementListRsp rsp = new AgreementListRsp();
                    BeanUtils.copyProperties(bo, rsp);
                    return rsp;
                }).toList();
        return ResultData.success(agreementListRspList);
    }

    /**
     * 详情
     *
     * @param agreementDetailReq
     * @return
     */
    @Override
    public ResultData detail(AgreementDetailReq agreementDetailReq) {
        Long id = agreementDetailReq.getId();
        if (null == id) {
            throw new BusinessException("未指定合同", HttpStatus.BAD_REQUEST);
        }
        AgreementPO agreementPO = agreementMapper.queryById(id);
        if (null == agreementPO) {
            throw new BusinessException("合同不存在", HttpStatus.BAD_REQUEST);
        }

        AgreementDetailRsp rsp = new AgreementDetailRsp();
        BeanUtils.copyProperties(agreementPO, rsp);
        List<AgreementAttributePO> agreementAttributePOList = agreementAttributeMapper.queryByAgreementId(id);
        List<AgreementAttributeVO> agreementAttributeList = Optional.ofNullable(agreementAttributePOList)
                .orElse(new ArrayList<>())
                .stream().map(po -> {
                    AgreementAttributeVO vo = new AgreementAttributeVO();
                    vo.setAttributeCode(po.getAttributeCode());
                    vo.setAttributeValue(po.getAttributeValue());
                    return vo;
                }).toList();
        rsp.setAgreementAttributeList(agreementAttributeList);

        List<AgreementAttachFilePO> agreementAttachFilePOList = agreementAttachFileMapper.queryByAgreementId(id);
        if (!CollectionUtils.isEmpty(agreementAttachFilePOList)) {
            List<AttachFilePO> attachFilePOList = attachFileMapper.queryByIds(agreementAttachFilePOList.stream().map(AgreementAttachFilePO::getAttachFileId).collect(Collectors.toList()));
            List<AttachFileVO> attachFileVOList = Optional.ofNullable(attachFilePOList)
                    .orElse(new ArrayList<>())
                    .stream().map(po -> {
                        AttachFileVO vo = new AttachFileVO();
                        BeanUtils.copyProperties(po, vo);
                        return vo;
                    }).toList();
            rsp.setAttachFileVOList(attachFileVOList);
        }
        return ResultData.success(rsp);
    }

    /**
     * 新增
     *
     * @param agreementAddReq
     * @return
     */
    @Override
    @Transactional
    public ResultData add(AgreementAddReq agreementAddReq) {
        Long agreementTypeId = agreementAddReq.getAgreementTypeId();
        if (null == agreementTypeId) {
            throw new BusinessException("未指定合同类别", HttpStatus.BAD_REQUEST);
        }

        String agreementName = agreementAddReq.getAgreementName();
        if (null == agreementName) {
            throw new BusinessException("合同名称不能为空", HttpStatus.BAD_REQUEST);
        }

        Date agreementSignDate = agreementAddReq.getAgreementSignDate();
        if (null == agreementSignDate) {
            throw new BusinessException("合同签署日期不能为空", HttpStatus.BAD_REQUEST);
        }

        Date agreementStartDate = agreementAddReq.getAgreementStartDate();
        if (null == agreementStartDate) {
            throw new BusinessException("合同生效日期不能为空", HttpStatus.BAD_REQUEST);
        }

        Date agreementEndDate = agreementAddReq.getAgreementEndDate();
        if (null == agreementEndDate) {
            throw new BusinessException("合同截止日期不能为空", HttpStatus.BAD_REQUEST);
        }

        List<Long> attachFileIdList = agreementAddReq.getAttachFileIdList();
        if (CollectionUtils.isEmpty(attachFileIdList)) {
            throw new BusinessException("合同附件不能为空", HttpStatus.BAD_REQUEST);
        }

        List<AgreementAttributeVO> agreementAttributeList = agreementAddReq.getAgreementAttributeList();
        if (CollectionUtils.isEmpty(agreementAttributeList)) {
            throw new BusinessException("未设置合同属性", HttpStatus.BAD_REQUEST);
        }

        SystemAgreementTypePO systemAgreementTypePO = systemAgreementTypeMapper.queryById(agreementTypeId);
        if (null == systemAgreementTypePO) {
            throw new BusinessException("合同类别不存在", HttpStatus.BAD_REQUEST);
        }

        // 合同主表
        AgreementPO agreementPO = new AgreementPO();
        BeanUtils.copyProperties(agreementAddReq, agreementPO);
        agreementMapper.insertSelective(agreementPO);

        // 合同属性
        List<SystemAgreementAttributePO> systemAgreementAttributePOList = systemAgreementAttributeMapper.queryByTypeId(agreementTypeId);
        if (systemAgreementAttributePOList.size() != agreementAttributeList.size()) {
            throw new BusinessException("合同属性变化，请刷新重新填写", HttpStatus.BAD_REQUEST);
        }
        Map<String, SystemAgreementAttributePO> systemAgreementAttributePOMap = systemAgreementAttributePOList.stream()
                .collect(Collectors.toMap(SystemAgreementAttributePO::getAttributeCode, obj -> obj, (v1, v2) -> v2));
        List<AgreementAttributePO> agreementAttributePOList = new ArrayList<>();
        for (AgreementAttributeVO agreementAttributeVO : agreementAttributeList) {
            String attributeCode = agreementAttributeVO.getAttributeCode();
            if (null == attributeCode) {
                throw new BusinessException("未指定合同属性", HttpStatus.BAD_REQUEST);
            }
            SystemAgreementAttributePO systemAgreementAttributePO = systemAgreementAttributePOMap.get(attributeCode);
            if (null == systemAgreementAttributePO) {
                throw new BusinessException("不存在的合同属性", HttpStatus.BAD_REQUEST);
            }

            String attributeValue = agreementAttributeVO.getAttributeValue();
            if (systemAgreementAttributePO.getAttributeRequired() == 1 && null == attributeValue) {
                throw new BusinessException("合同属性值不能为空", HttpStatus.BAD_REQUEST);
            }

            AgreementAttributePO po = new AgreementAttributePO();
            po.setAgreementId(agreementPO.getId());
            po.setAttributeCode(attributeCode);
            po.setAttributeValue(attributeValue);
            agreementAttributePOList.add(po);
        }
        agreementAttributeMapper.insertRecords(agreementAttributePOList);

        // 合同附件表
        List<AgreementAttachFilePO> agreementAttachFilePOList = new ArrayList<>();
        for (Long attachFileId : attachFileIdList) {
            AgreementAttachFilePO agreementAttachFilePO = new AgreementAttachFilePO();
            agreementAttachFilePO.setAgreementId(agreementPO.getId());
            agreementAttachFilePO.setAttachFileId(attachFileId);
            agreementAttachFilePOList.add(agreementAttachFilePO);
        }
        agreementAttachFileMapper.insertRecords(agreementAttachFilePOList);

        return ResultData.success();
    }

    /**
     * 更新
     *
     * @param agreementUpdateReq
     * @return
     */
    @Override
    public ResultData update(AgreementUpdateReq agreementUpdateReq) {
        return null;
    }

    /**
     * 删除
     *
     * @param agreementDeleteReq
     * @return
     */
    @Override
    @Transactional
    public ResultData delete(AgreementDeleteReq agreementDeleteReq) {
        Long id = agreementDeleteReq.getId();
        if (null == id) {
            throw new BusinessException("未指定合同", HttpStatus.BAD_REQUEST);
        }
        agreementComponent.deleteAgreementById(id);
        return ResultData.success();
    }
}